// pages/common/login/login.js
const app = getApp();
let api = require("../../../requests/api.js");
let cache = require('../../../utils/cache.js');
import util from '../../../utils/util.js'

Page({

  /**
   * Page initial data
   */
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    fixed: true,
    color: '#000000', //#ffffff
    touchStartY: 0, //触摸开始的Y坐标
    toggleBarShow: false,
    backStyle: 'normal',
    backEvent: false,
    backHomeEvent: false,
    dialogvisible: false,
    closeOnClickModal: false,
    showConfirm: false,
    showCancel: false,
    openId: "", //标识用户信息
    loginCode: "",
    fromNewUser: false
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    console.log('options.fromNewUser' + options.fromNewUser)
    new app.WeToast();
    //判断是否是从新人逻辑过来
    if (options.fromNewUser) {
      this.setData({
        fromNewUser: true
      })
    }
    this.checkcode2Session((res) => {
      console.log('openId:' + res)
    })
  },
  //
  checkcode2Session: function(successCallback) {
    var that = this;
    //检查是否登录过期
    wx.checkSession({
      success: function(res) {
        console.log('登录界面，登录未过期')
        //进入页面先取缓存
        wx.getStorage({
          key: 'openId',
          success: function(res) {
            console.log('取出缓存openId' + res.data)
            that.setData({
              loginCode: res.data
            })
            util.isFunction(successCallback) && successCallback(res.data);
          },
          fail: function(res) {
            console.log('s:获取失败')
            wx.login({
              success: (ev) => {
                var code = ev.code
                that.code2Session(code, (res) => {
                  that.setData({
                    loginCode: res
                  })
                  util.isFunction(successCallback) && successCallback(res);
                })
              }
            })
          }
        })
      },
      fail: function(res) {
        console.log('登录界面，登录已过期，重新取code')
        wx.login({
          success: (ev) => {
            var code = ev.code
            that.code2Session(code, (res) => {
              util.isFunction(successCallback) && successCallback(res);
            })
          }
        })
      }
    })
  },
  code2Session: function(code, successCallback) {
    var params = {
      code: code
    }
    api.post_code2Session(params, (res) => {
      console.log(res)
      if (res.data) {
        wx.setStorage({
          key: 'openId',
          data: res.data.openId
        })
        util.isFunction(successCallback) && successCallback(res.data.openId);
      }
    }, () => {

    }, () => {

    });
  },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {},

  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      var userInfo = e.detail
      console.log(e.detail)
      that.checkcode2Session((res) => {
        console.log('openId:' + res)
        wx.getUserInfo({
          success: function(userData) {
            userInfo = userData
            userInfo.openId = res
            that.requestCheckMobileAuth(userInfo)

          }
        })
      })

    } else {
      //用户按了拒绝按钮
    }
  },

  getPhoneNumber: function(e) {
    var that = this;
    //同意手机授权
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      var userInfo = e.detail
      var params = {
        encryptedData: userInfo.encryptedData,
        iv: userInfo.iv,
      };
      that.checkcode2Session((res) => {
        console.log('openId:' + res)
        params.openId = res
        that.appLogin(params)
      })

    } else { //授权失败直接登录
      that.appLogin({})
    }
  },

  requestCheckMobileAuth: function(userInfo) {
    const that = this;
    var params = {
      openId: userInfo.openId,
      encryptedData: userInfo.encryptedData,
      iv: userInfo.iv
    };
    api.post_checkMobileAuth(params,
      (data) => {
        if (data.resCode == '0') {
          this.setData({
            openId: userInfo.openId
          })
          //是否需要手机授权
          if (data.data.mobileAuthFlag) {
            //调用登录接口
            this.showDialog()

          } else {
            this.appLogin({})
          }
        }
      },
      (error) => {
        if (util.alertNetworkError(error)) {
          that.wetoast.toast({
            title: error.resMsg,
          })
        }
        console.log(error)
      },
      (data) => {

      }
    )
  },

  appLogin: function(userInfo) {
    console.log(this.data.openId)
    var that = this;
    //插入登录的用户的相关信息到数据库
    userInfo.openId = this.data.openId
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '',
    })
    api.login(userInfo,
      (data) => {
        wx.hideLoading()
        wx.hideNavigationBarLoading()
        if (data.resCode == '0') {
          wx.setStorage({
            key: 'endUser',
            data: data.data
          })
          cache.endUser = data.data
          //裁剪头像
          var res = wx.getSystemInfoSync()
          let pixelRatio = res.pixelRatio
          let windowWidth = res.windowWidth
          if (typeof cache.endUser.avatar == 'string') {
            let clipUrl = util.clipimage(cache.endUser.avatar + "", util.rpx2px(125))
            cache.endUser.avatar = clipUrl
          }
          wx.showToast({
            title: '登录成功',
            duration: 1500,
            success: function() {
              setTimeout(function() {
                if (that.data.fromNewUser) {
                  app.globalData.getCoupon = true
                  wx.switchTab({
                    url: '/pages/home/home',
                  })
                } else {
                  var pages = getCurrentPages();
                  if (pages.length > 1) {
                    wx.navigateBack({
                      delta: 1
                    })
                  } else {
                    wx.switchTab({
                      url: '/' + app.globalData.route,
                    })
                  }
                }

              }, 1500);
            }
          })
        }
      },
      (error) => {
        wx.hideLoading()
        wx.hideNavigationBarLoading()
        if (util.alertNetworkError(error)) {
          that.wetoast.toast({
            title: error.resMsg,
          })
        }
        console.log(error)
      },
      (data) => {
        wx.hideLoading()
        wx.hideNavigationBarLoading()
      }
    )
  },

  bindBack: function() {
    if (this.data.fromNewUser) {
      wx.navigateTo({
        url: '../login/telLogin?newUser=' + true,
      })
    } else {
      wx.navigateTo({
        url: '../login/telLogin?newUser=' + false,
      })
    }

  },
  xieyiClick: function() {
    wx.navigateTo({
      url: '../login/userAgreement',
    })

  },

  // 弹窗
  showDialog: function() {
    this.setData({
      dialogvisible: true
    })
  },
  closeDialog: function() {
    this.setData({
      dialogvisible: false
    })
  },
  confirmClick: function() {
    this.closeDialog()
  },
  cancelClick: function() {
    this.closeDialog()
    this.appLogin({})
  }
})